package com.xhtech.lib_ui.view.discussionavatarview

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Color
import android.os.Handler
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.annotation.DrawableRes
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.xhtech.base.R
import com.xhtech.base.view.discussionavatarview.*
import java.util.*

/**
 * Created by HARRY on 2019/1/18 0018.
 */
class DiscussionAvatarView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : ViewGroup(context, attrs, defStyleAttr) {

    /**
     * 头像的半径
     */
    private var mRadius = 0

    /**
     * 头像间的距离
     */
    private var mSpace = 0f
    private var mContext: Context? = null
    private var mInflater: LayoutInflater? = null

    /**
     * 是否最后一个显示完全
     */
    private var mIsLastComplete = false

    /**
     * 最大头像数目
     */
    private var mMaxCount = 0

    /**
     * 当前移动的偏移量
     */
    private var mCurrentOffset = 0

    /**
     * 移动的属性动画
     */
    private var animator: ValueAnimator? = null

    /**
     * 是否显示动画效果
     */
    private var mIsShowAnimation = false
    private val mIsShowAddMoreIcon = true

    /**
     * 监听
     */
    private var listener: DiscussionAvatarListener? = null
    private var mIsShowFrame = false
    private var mFrameColor = 0
    private val animHelper: AvatarAnimHelper by lazy { AvatarAnimHelper(this) }
    var animSet = arrayListOf<ObjectAnimator>()
    val ivList = arrayListOf<ImageView>()
    var mHandler: Handler? = null
    private fun initView(context: Context, attrs: AttributeSet?) {
        mContext = context
        mInflater = LayoutInflater.from(mContext)
        val array = context.obtainStyledAttributes(attrs, R.styleable.DiscussionAvatarView)
        if (array != null) {
            val radius = array.getInteger(R.styleable.DiscussionAvatarView_radius, 13)
            mSpace = array.getFloat(R.styleable.DiscussionAvatarView_space, 0.5.toFloat())
            mMaxCount = array.getInteger(R.styleable.DiscussionAvatarView_maxCount, 6)
            mIsLastComplete = array.getBoolean(R.styleable.DiscussionAvatarView_isLastComplete, true)
            mIsShowAnimation = array.getBoolean(R.styleable.DiscussionAvatarView_isShowAnimation, true)
            mIsShowFrame = array.getBoolean(R.styleable.DiscussionAvatarView_isShowFrame, true)
            mFrameColor = array.getColor(R.styleable.DiscussionAvatarView_frameColor, Color.RED)
            mRadius = DensityUtil.dip2px(context, radius.toFloat())
            array.recycle()
        }
//        mHandler = Handler()
//        handler=Handler()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val heiMeasure = MeasureSpec.getSize(heightMeasureSpec)
        val heiMode = MeasureSpec.getMode(heightMeasureSpec)
        val widMode = MeasureSpec.getMode(widthMeasureSpec)
        val widMeasure = MeasureSpec.getSize(widthMeasureSpec)
        var wid = 0
        var hei = 0
        val count = childCount
        for (i in 0 until count) {
            val child = getChildAt(i)
            val lp = child.layoutParams
            lp.width = 2 * mRadius
            lp.height = lp.width
            child.layoutParams = lp
            // 测量子View的宽和高,系统提供的measureChild
            measureChild(child, widthMeasureSpec, heightMeasureSpec)
            // 子View占据的宽度
            val childWidth = child.measuredWidth
            // 子View占据的高度
            val childHeight = child.measuredHeight
            if (i < mMaxCount) {
                wid = if (i == 0) {
                    wid + childWidth
                } else {
                    (wid + childWidth * mSpace).toInt()
                }
            }
            hei = Math.max(hei, childHeight)
        }
        //如果是exactly使用测量宽和高，否则使用自己设置的宽和高
        setMeasuredDimension(if (widMode == MeasureSpec.EXACTLY) widMeasure else wid,
                if (heiMode == MeasureSpec.EXACTLY) heiMeasure else hei)
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        val count = childCount
        var left = -mCurrentOffset
        val top = 0
        var right = -mCurrentOffset
        for (i in 0 until count) {
            var child: View
            child = if (mIsLastComplete) {
                getChildAt(i)
            } else {
                getChildAt(count - i - 1)
            }
            val childWidth = child.measuredWidth
            val childHeight = child.measuredHeight
            right = if (i == 0) {
                right + childWidth
            } else {
                (right + childWidth * mSpace).toInt()
            }
            child.layout(left, top, right, childHeight)
            left = (left + childWidth * mSpace).toInt()
        }
    }

    /**
     * 初始化数据
     *
     * @param list
     */
    fun initDatas(list: ArrayList<String>) {
        if (list == null) {
            return
        }
        removeAllViews()
        val size = list.size
        mMaxCount = size
        for (i in 0 until size) {
            val iv = mInflater!!.inflate(R.layout.avatar, this, false) as ImageView
            val item = if (mIsLastComplete) {
                list[i]
            } else {
                list[size - i - 1]
            }
            GlideUtil.loadCircleImageView(mContext, item, iv, mIsShowFrame, mFrameColor)
//            iv.alpha=0f
            this.addView(iv)
            ivList.add(iv)
        }
//        animHelper?.startPetHeadAlphaAnim(animSet, ivList)
//        initDataList(list)
    }

    fun showMoreImg(@DrawableRes more: Int) {
        mMaxCount++
        val iv = mInflater!!.inflate(R.layout.avatar, this, false) as ImageView
        Glide.with(context).load(more).transform(GlideCircleTransform(context)).diskCacheStrategy(DiskCacheStrategy.RESOURCE).into(iv)
        this.addView(iv)
    }
    /**
     * 添加一个头像，有动画监听
     *
     * @param ava
     */
    /**
     * 添加头像，没有动画监听
     *
     * @param ava
     */
    @JvmOverloads
    fun addData(ava: String?, listener1: DiscussionAvatarListener? = null) {
        listener = listener1
        if (mMaxCount <= 0) {
            return
        }
        if (TextUtils.isEmpty(ava)) {
            return
        }
        if (animator != null) {
            animator!!.cancel()
        }
        val childCount = childCount
        val iv = mInflater!!.inflate(R.layout.avatar, this, false) as ImageView
        GlideUtil.loadCircleImageView(mContext, ava, iv, mIsShowFrame, mFrameColor)
        if (mIsLastComplete) {
            this.addView(iv)
        } else {
            this.addView(iv, 0)
        }
        if (childCount >= mMaxCount) {
            if (mIsShowAnimation) {
                val countAft = getChildCount()
                val child: View
                child = if (mIsLastComplete) {
                    getChildAt(0)
                } else {
                    getChildAt(countAft - 1)
                }
                val childWid = child.measuredWidth
                animator = ValueAnimator.ofInt(0, (childWid * mSpace).toInt())
                animator?.duration = 1000
                animator?.addUpdateListener(ValueAnimator.AnimatorUpdateListener { animation ->
                    mCurrentOffset = animation.animatedValue as Int
                    //使左侧渐变消失，右侧渐变显示
                    val duration = animation.duration
                    val currentPlayTime = animation.currentPlayTime
                    val v = currentPlayTime.toFloat() / duration
                    iv.alpha = v
                    child.alpha = 1 - v
                    requestLayout()
                })
                animator?.addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationStart(animation: Animator) {
                        super.onAnimationStart(animation)
                        if (listener != null) {
                            listener!!.onAnimationStart()
                        }
                    }

                    override fun onAnimationEnd(animation: Animator) {
                        super.onAnimationEnd(animation)
                        mCurrentOffset = 0
                        val count = getChildCount()
                        for (i in 0 until count) {
                            val child = getChildAt(i)
                            child.alpha = 1f
                        }
                        if (mIsLastComplete) {
                            removeViewAt(0)
                        } else {
                            removeViewAt(count - 1)
                        }
                        if (listener != null) {
                            listener!!.onAnimationEnd()
                        }
                    }
                })
                animator?.start()
            } else {
                mCurrentOffset = 0
                if (mIsLastComplete) {
                    removeViewAt(0)
                } else {
                    val count = getChildCount()
                    removeViewAt(count - 1)
                }
            }
        }
    }

    /**
     * 设置最大头像数
     *
     * @param count
     */
    fun setMaxCount(count: Int) {
        mMaxCount = count
        val childCount = childCount
        if (childCount > mMaxCount) {
            for (i in 0 until childCount - mMaxCount) {
                if (mIsLastComplete) {
                    removeViewAt(0)
                } else {
                    val currentCount = getChildCount()
                    removeViewAt(currentCount - 1)
                }
            }
        }
    }

    override fun removeAllViews() {
        clearAnimSet()
        ivList.clear()
        super.removeAllViews()
    }
    /**
     * 清空动画集
     */
     fun clearAnimSet() {
        for (anim in animSet) {
            anim.pause()
        }
        animSet.clear()
    }

    init {
        initView(context, attrs)
    }
}